<?php
include 'lib/controllerWithoutGetOrPost.php';
include 'lib/LoggedIn.php';
$loggedIn = new LoggedIn();
$loggedIn->setPermission = "Admin Area";
include("../authenticationEmail.php");
include("header2.php");
function setUsernameAndEmail($userId, $username, $email)
{
    global $db;
    $sql = <<< EOT
        UPDATE Users
        SET
            Username = '%s',
            Email = '%s'
        WHERE ID = %d
EOT;
    $sql = sprintf($sql,
        $db->escape($username),
        $db->escape($email),
        intval($userId)
    );
    $result = $db->query($sql);
    return $result === TRUE;
}
function updateUsernameAndEmail($userId, $username, $email)
{
    $success = setUsernameAndEmail($userId, $username, $email);
    if ($success) {
        echo '<p>User details updated successfully.</p>';
    } else {
        echo '<p>Failed to update user details!</p>';
    }
    $self = $_SERVER['PHP_SELF'];
    echo '<a href="'.$self.'">Back to Users</a>';
}
function getUsersDetails($userId)
{
    global $db;
    $user = array();
    $sql = <<< EOT
        SELECT ID, Enable, Username, Password, Email, AuthID
        FROM Users
        WHERE ID = %d
EOT;
    $sql = sprintf($sql, intval($userId));
    $result = $db->query($sql);
    if ($db->rowCount($result) > 0) {
        $user = $db->fetch($result);
    }
    return array(
        'ID' => intval($user['ID'])
      , 'Enable' => intval($user['Enable'])
      , 'Username' => $db->unescape($user['Username'])
      , 'Password' => $db->unescape($user['Password'])
      , 'Email' => $db->unescape($user['Email'])
      , 'AuthId' => $db->unescape($user['AuthId'])
    );
}
function editUserDetails($userId)
{
    $user = getUsersDetails($userId);
    $username = $user['Username'];
    $email = $user['Email'];
    echo <<< EOT
    <h3>Edit Account</h3>
    <form method="post" action="userlist.php">
        <input type="hidden" name="action" value="update">
        <input type="hidden" name="userid" value="$userId">
        Username: <input type="text" name="username" value="$username"><br />
        <br />
        Email: <input type="text" name="email" value="$email"><br />
        <br />
        <input type="submit" value="Modify Details">
    </form>
    <a href="userlist.php">Back to Users</a>

EOT;
}
function enableUser($userId)
{
    global $db;
    $sql = <<< EOT
        UPDATE Users
        SET Enable = '1'
        WHERE ID = %d
EOT;
    $sql = sprintf($sql, $userId);
    $result = $db->query($sql);
    return $result === TRUE;
}
function cancelAuth($userId)
{
    global $db;
    $sql = <<< EOT
        UPDATE Users
        SET AuthId = NULL
        WHERE ID = %d
EOT;
    $sql = sprintf($sql, $userId);
    $result = $db->query($sql);
    return $result === TRUE;
}
function setAuthorisationCode($userId)
{
    $authCode = crypt((string)$userId);
    $authId = insertAuthCode($authCode);
    setUserAuthId($userId, $authId);
}
function performEnableUser($userId)
{
    $user = getUsersDetails($userId);
    $username = $user['Username'];
    $email = $user['Email'];
    if(empty($email)) {
        echo "The account needs an email before it can be enabled!";
    } else {
        $success = enableUser($userId);
        if (!$success) {
            echo 'Failed to Enable account!!';
        } else {
            echo 'User '.$userId.' Enabled.';
            //GEN ACTIVATION LINK AND MAIL THEM HERE
            setAuthorisationCode($userId);
            $message = activationEmailMessage($userId, $username, $authCode);
            sendAuthEmail($email, 'A Memory Tree Authentication Email', $message);
            echo <<< EOT
            <p>The Authentication email has been sent to $username</p>
            <p><a href="userlist.php">Back to Users</a></p>

EOT;
        }
    }
}
function performCancelAuth($userId)
{
    $success = cancelAuth($userId);
    if (!$success) {
        echo 'Failed to Cancel authorisation!!';
    } else {
        echo <<< EOT
        <p>The authentication for that account has been cancelled.</p>
        <p><a href="userlist.php">Back to Users</a></p>

EOT;
    }
}
function confirmEnableUser($userId)
{
    $user = getUsersDetails($userId);
    $username = $user['Username'];
    $enable = $user['Enable'];
    $authId = $user['AuthId'];
    if (empty($user['Enable']) || empty($user['Password'])) {
        echo <<< EOT
        <form method="post" action="userlist.php">
            <input type="hidden" name="action" value="enable">
            <input type="hidden" name="userid" value="$userId">
            Are you sure you want to enable $username?<br />
            <input type="submit" value="Enable" />
        </form>
        
EOT;
    } else if ($user['AuthId']) {
        echo <<< EOT
        <form method="post" action="userlist.php">
            <input type="hidden" name="action" value="enable">
            <input type="hidden" name="userid" value="$userId">
            Are you sure you want to send another mail to $username?<br />
            <input type="submit" value="Resend" />
        </form>

EOT;
    } else {
        echo <<< EOT
        <br />
        $username has already been enabled!
        
EOT;
    echo <<< EOT
        <p><a href="userlist.php">Back to Users</a></p>

EOT;
    }
}
function confirmCancelAuth($userId)
{
    $user = getUsersDetails($userId);
    $username = $user['Username'];
    $enable = $user['Enable'];
    $authId = $user['AuthId'];
    echo <<< EOT
        <form method="post" action="userlist.php">
            <input type="hidden" name="action" value="cancel">
            <input type="hidden" name="userid" value="$userId">
            Please confirm that you wish to cancel the authentication that's assigned to $username<br />
            <input type="submit" value="Cancel authentication" />
        </form>
        
EOT;
}
function importFuneralHomes()
{
    $count=0;
    $query = "SELECT `ID`, `FuneralHomeID`, `Email` FROM `FuneralDetails`";
    $result = mysql_query($query);
    while ($FDdetail = mysql_fetch_assoc($result)) {
        $query1 = "SELECT `ID` FROM `Users` WHERE `FuneralHomeID` = '".$FDdetail['FuneralHomeID']."'";
        $result1 = mysql_query($query1);
        $CurrUser = mysql_fetch_assoc($result1);
        if(!$CurrUser['ID']){
            $query2 = "SELECT `Name` FROM `FuneralHome` WHERE `ID` = '".$FDdetail['FuneralHomeID']."'";
            $result2 = mysql_query($query2);
            $FH = mysql_fetch_assoc($result2);
            $newUserName=str_replace("'","",$FH['Name']);
            $newUserName=strtolower($newUserName);
            $query3="INSERT INTO `$dbname`.`Users` (`ID`, `Enable`, `FuneralHomeID`, `Username`, `Password`, `Permissions`, `Type`, `Email`, `AutoMail`) VALUES (NULL , '0', '".$FDdetail['FuneralHomeID']."', '$newUserName', '', 'FD Submit', 'Director', '".$FDdetail['Email']."', '1');";
            if($result3 = mysql_query($query3)){$count++;}
        }
    }
    if (!empty($count)) {
        echo "<br />".$count." new accounts added.";
    }
}
function hideGroupForm()
{
    $checkboxes = '';
    foreach(groupTypes() as $group) {
        $type = $group['type'];
        $checked = ($_GET[$type]) ? ' checked="checked"' : '';
        $heading = $group['heading'];
        $checkboxes .= <<< EOT
        <input type="checkbox" name="$type" value="no"$checked> $heading
        
EOT;
    }
    return <<< EOT
    <form method="get" action="$self">
        Hide these groups:
        $checkboxes
        <input type="submit" value="Hide">
    </form>

EOT;
}
function groupTypes()
{
    return array(
        array('type' => 'error',          'heading' => 'Error',            'color' => 'red'),
        array('type' => 'authenticating', 'heading' => 'Authenticating',   'color' => 'lime'),
        array('type' => 'activated',      'heading' => 'Activated',        'color' => 'white'),
        array('type' => 'disabled',       'heading' => 'Disabled',         'color' => 'yellow'),
        array('type' => 'noemail',        'heading' => 'No Email Address', 'color' => 'orange')
    );
}
function groupHeading($type)
{
    $heading = '';
    foreach(groupTypes() as $group) {
        if ($type == $group['type']) {
            $heading = $group['heading'];
        }
    }
    return $heading;
}
function rowType($color)
{
    $type = '';
    foreach(groupTypes() as $group) {
        if ($color == $group['color']) {
            $type = $group['type'];
        }
    }
    return $type;
}
function rowColor($type)
{
    $color = '';
    foreach(groupTypes() as $group) {
        if ($type == $group['type']) {
            $color = $group['color'];
        }
    }
    return $color;
}
function userBgColor($enabled, $password, $email, $authId)
{
    $bgcolor = rowColor('error');
    if(!$password && $authId) {
        $bgcolor = rowColor('authenticating');
    } else if ($enabled && $password && $email && !$authId) {
        $bgcolor = rowColor('activated');
    } else if (!$enabled && $email) {
        $bgcolor = rowColor('disabled');
    } else if (!$enabled && !$email) {
        $bgcolor = rowColor('noemail');
    }
    return $bgcolor;
}
function userActions($userId, $enabled, $password, $authId, $time)
{
    $actions = '<a href="userlist.php?action=edit&amp;userid='.$userId.'">Edit</a>';
    if (!$enabled || !$password || $authId) {
        if(empty($authId)) {
            $actions .= ' | <a href="userlist.php?action=enable&amp;userid='.$userId.'">Enable</a>';
        } else if($enabled && $password && $authId) {
            $actions .= ' | <a href="userlist.php?action=cancel&amp;userid='.$userId.'">Cancel</a>';
        } else {
            $actions .= ' | <a href="userlist.php?action=enable&amp;userid='.$userId.'">Resend</a> Last sent: '.$time;
        }
    }
    return $actions;
}
function createList()
{
    $list = array();
    foreach (groupTypes() as $types) {
        $type = $types['type'];
        $list[$type] = array();
    }
    return $list;
}
function userRow($bgcolor, $userId, $username, $email, $actions)
{
    return <<< EOT
        <tr bgcolor="$bgcolor">
            <td>$userId</td>
            <td><a href="usersubmissions.php?userid="$userId">$username</a></td>
            <td>$email</td>
            <td>$actions</td>
        </tr>

EOT;
}
function rowHeading($heading)
{
    $heading = groupHeading($heading);
    return <<< EOT
        <tr>
            <td colspan="4"><h3>$heading</h3></td>
        </tr>

EOT;
}
function userTable($type, $group)
{
    $rowHeading = rowHeading($type);
    $rows = '';
    foreach ($group as $row) {
        $rows .= $row;
    }
    return <<< EOT
        $rowHeading
        <tr>
            <th>ID</th>
            <th>Username</th>
            <th>Email</th>
            <th>Actions</th>
        </tr>
        $rows        

EOT;
}
function listUsers()
{
    $self = $_SERVER['PHP_SELF'];
    $hideGroup = hideGroupForm();
    echo <<< EOT
<div>
    $hideGroup
    <table>

EOT;
    $list = array(
        'error' => array(),
        'authenticating' => array(),
        'activated' => array(),
        'disabled' => array(),
        'noemail' => array()
    );
    $query = <<< EOT
        SELECT Users.ID, Enable, Username, Password, Email, AuthId, Time
        FROM Users
            LEFT OUTER JOIN Authentication
                ON Users.AuthId = Authentication.ID
        ORDER BY Enable DESC, AuthId Desc, Username ASC
EOT;
    $result = mysql_query($query);
    $list = createList();
    while ($user = mysql_fetch_assoc($result)) {
        $userId = $user['ID'];
        $enabled = $user['Enable'];
        $username = $user['Username'];
        $password = $user['Password'];
        $email = $user['Email'];
        $authId = $user['AuthId'];
        $time = $user['Time'];
        $bgcolor = userBgColor($enabled, $password, $email, $authId);
        $actions = userActions($userId, $enabled, $password, $authId, $time);
        $row = userRow($bgcolor, $userId, $username, $email, $actions);
        $rowType = rowType($bgcolor);
        array_push($list[$rowType], $row);
    }
    foreach ($list as $type => $group) {
        if (count($group) > 0 && $_GET[$type] != 'no') {
            echo userTable($type, $group);
        }
    }
    echo <<< EOT
    </table>
</div>

EOT;
}
if(!$loggedIn->check()) {
    echo $loggedIn->message();
} else {
    $action = $_POST['action'];
    $userId = $_POST['userid'];
    $username = $_POST['username'];
    $email = $_POST['email'];
    switch ($action) {
        case 'update':
            updateUsernameAndEmail($userId, $username, $email);
            break;
        case 'enable':
            performEnableUser($userId);
            break;
        case 'cancel':
            performCancelAuth($userId);
            break;
        default:
            $action = $_GET['action'];
            $userId = $_GET['userid'];
            switch ($action) {
                case 'edit':
                    editUserDetails($userId);
                    break;
                case 'enable':
                    confirmEnableUser($userId);
                    break;
                case 'cancel':
                    confirmCancelAuth($userId);
                    break;
                default:
                    importFuneralHomes();
                    listUsers();
                }
    }
}
?>
